<template>
  <!-- 上传组件 -->
  <el-upload
    ref="upload"
    v-model="imgUrl"
    class="upload-demo"
    :before-upload="handleBeforeUpload"
    :http-request="uploadFile"
    :limit="1"
    :on-exceed="handleExceed"
    :auto-upload="false"
    list-type="picture"
  >
    <template #trigger>
      <el-button type="primary">选择要上传的图片</el-button>
    </template>
    <el-button v-if="!callbackUpload" class="ml-3" type="success" @click="submitUpload">
      点击上传
    </el-button>
    <template #tip>
      <div class="el-upload__tip text-red">仅限1张图片(大小不超过1M)，新的图片会覆盖旧图片</div>
    </template>

    <!-- <img v-if='imgUrl' :src='imgUrl' class='single-uploader__image'> -->
    <!-- <el-icon v-else class='single-uploader__icon'>
      <i-ep-plus />
    </el-icon> -->
  </el-upload>
</template>

<script setup lang="ts">
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
import { UploadRequestOptions, genFileId } from 'element-plus';
import { uploadFileApi } from '@/api/file';
const upload = ref<UploadInstance>();
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  // 通过回调上传文件
  callbackUpload: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue']);
const imgUrl = useVModel(props, 'modelValue', emit);

/**
 * 自定义图片上传
 *
 * @param options
 */
async function uploadFile(options: UploadRequestOptions): Promise<any> {
  const { data: fileInfo } = await uploadFileApi(options.file);
  imgUrl.value = fileInfo.url;
}

/**
 * 限制用户上传文件的格式和大小
 */
function handleBeforeUpload(file: UploadRawFile) {
  if (file.size > 1 * 1048 * 1048) {
    ElMessage.warning('上传图片不能大于1M');
    return false;
  }
  return true;
}

const handleExceed: UploadProps['onExceed'] = files => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

const submitUpload = () => {
  upload.value!.submit();
};
</script>

<style scoped lang="scss">
// .single-uploader {
//   overflow: hidden;
//   cursor: pointer;
//   border: 1px var(--el-border-color) solid;
//   border-radius: 6px;

//   &:hover {
//     border-color: var(--el-color-primary);
//   }

//   &__image {
//     display: block;
//     width: 178px;
//     height: 178px;
//   }

//   &__icon {
//     width: 178px;
//     height: 178px;
//     font-size: 28px;
//     color: #8c939d;
//     text-align: center;
//   }
// }
</style>
